﻿using System.Diagnostics.CodeAnalysis;
using System.Reflection;

namespace Devonline.Core;

public class MemberEqualityComparer<T> : IEqualityComparer<T>
{
    public bool Equals(T? x, T? y)
    {
        var propertyInfos = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (var propertyInfo in propertyInfos)
        {
            var valueX = propertyInfo.GetValue(x);
            var valueY = propertyInfo.GetValue(y);
            if (!(propertyInfo.PropertyType.IsValueType || valueX == valueY) || (propertyInfo.PropertyType.IsValueType && valueX?.ToString() != valueY?.ToString()))
            {
                return false;
            }
        }

        return true;
    }

    public int GetHashCode([DisallowNull] T obj) => obj.GetHashCode();
}